import { defineStore } from 'pinia'
import type { LoginResponse, User } from '@/services/account/account.types'

interface AccountStatus {
  access_token: string
  expires_in: number
  refresh_expires_in: number
  refresh_token: string
  user: User | null
}

export const useAccountStore = defineStore('account', {
  state: (): AccountStatus => ({
    access_token: '',
    expires_in: 0,
    refresh_expires_in: 0,
    refresh_token: '',
    user: null,
  }),

  getters: {
    isAuthenticated: (state) => !!state.access_token,
    getToken: (state) => state.access_token,
    getRefreshToken: (state) => state.refresh_token,
    getUser: (state) => state.user,
  },

  actions: {
    setTokens(response: LoginResponse) {
      this.access_token = response.access_token
      this.refresh_token = response.refresh_token
      this.expires_in = response.expires_in
      this.refresh_expires_in = response.refresh_expires_in

      localStorage.setItem('token', response.access_token)
      localStorage.setItem('refreshToken', response.refresh_token)
    },

    setUser(user: User) {
      this.user = user
    },

    loadTokens() {
      const token = localStorage.getItem('token')
      const refreshToken = localStorage.getItem('refreshToken')
      if (token && refreshToken) {
        this.access_token = token
        this.refresh_token = refreshToken
      }
    },

    clearAuth() {
      this.access_token = ''
      this.expires_in = 0
      this.refresh_expires_in = 0
      this.refresh_token = ''
      this.user = null

      localStorage.removeItem('token')
      localStorage.removeItem('refreshToken')
    },
  },
})
